package com.basic.ui.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.basic.ui.R
import com.basic.ui.anim.WindowAnim

/**
 * 支持dialog gravity(Top dialog, Bottom dilaog), dialog 动画
 *
 * @author Peter Liu
 * @since 2023/8/7 23:52
 *
 */

open class BaseDialogFragment : AppCompatDialogFragment() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /// must call before dialog create
        setStyle(STYLE_NO_TITLE, R.style.BasicUi_Dialog)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        initDialog(dialog)
        return dialog
    }

    protected open fun initDialog(dialog: Dialog) {
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialog?.window?.let {
            initWindow(it)
        }
        initView(view)
        initModel()
    }

    protected open fun initWindow(window: Window) {
        window.apply {
            setGravity(gravity())
            //// must call after dialog content view create
            setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            setWindowAnimations(windowAnimation())
        }
    }

    protected open fun initView(view: View) {

    }

    open fun initModel() {

    }


    protected open fun gravity(): Int {
        return Gravity.CENTER
    }

    protected open fun windowAnimation(): Int {
        return when (gravity()) {
            Gravity.CENTER -> {
                WindowAnim.CENTER_SCALE
            }

            Gravity.TOP -> {
                WindowAnim.TOP_STYLE
            }

            Gravity.BOTTOM -> {
                WindowAnim.BOTTOM_STYLE
            }

            else -> {
                -1
            }
        }
    }

    protected open fun tag(): String {
        return javaClass.name
    }

    fun show(activity: FragmentActivity) {
        show(activity.supportFragmentManager)
    }

    fun show(fragment: Fragment) {
        show(fragment.childFragmentManager)
    }

    open fun show(manager: FragmentManager?) {
        manager ?: return
        if (isAdded) {
            return
        }
        try {
            show(manager, tag)
        } catch (_: Exception) {
        }
    }

    override fun dismiss() {
        try {
            dismissAllowingStateLoss()
        } catch (_: Exception) {
        }
    }


}